package org.jground.rx.ui.zk;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Image;
import org.zkoss.zul.Messagebox;

public class UIMessageboxUtils {
    private static Log logger = LogFactory.getLog(UIMessageboxUtils.class);

    public static void showInfoMessage(String message) {
        try {
            Messagebox.show(message);
        } catch (InterruptedException e) {
            logger.error(e, e);
        }
    }

    public static void showInfoMessage(String title, String message) {
        try {
            Messagebox.show(message, title, Messagebox.OK, null);
        } catch (InterruptedException e) {
            logger.error(e, e);
        }
    }

    public static void showCheckOutFailed(String rxdSynopsis, String username) {
        showInfoMessage("Data for " + rxdSynopsis + " can not be opened or edit! Data is already checked out by: "
                + username);
    }

    public static boolean showQuestionMessage(String message, String title, Runnable yesRunnable, Runnable noRunnable) {
        try {
            final _MSGEventListener eventListener = new _MSGEventListener(yesRunnable, noRunnable);
            Messagebox.show(message, title, Messagebox.YES | Messagebox.NO, Messagebox.QUESTION, eventListener);
            return eventListener.answer;
        } catch (InterruptedException ex) {
            logger.error(ex, ex);
        }
        return false;
    }

    private static class _MSGEventListener implements EventListener {
        public boolean answer;

        private Runnable yesRunnable;
        private Runnable noRunnable;

        public _MSGEventListener(Runnable yesRunnable, Runnable noRunnable) {
            this.yesRunnable = yesRunnable;
            this.noRunnable = noRunnable;
        }

        public void onEvent(Event event) throws Exception {
            if (event.getName().equals(Events.ON_OK) || event.getName().equals("onYes")
                    || event.getName().equals("onOK")) {
                answer = true;
                yesRunnable.run();
            } else {
                answer = false;
                noRunnable.run();
            }
        }
    }

    public static void showImageMessage(Image image) {
        // Messagebox.show();
    }
}
